package com.iwdnb.gkgz.common.utils;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import com.iwdnb.bmnf.common.exception.ExceptionsEnhancer;
import com.iwdnb.bmnf.common.model.result.Result;
import com.iwdnb.bmnf.common.utils.HttpClientUtils;
import com.iwdnb.gkgz.common.enums.StockIndustryEnums;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 股票板块工具类，因api接口收费，弃用
 */
@Slf4j
@Deprecated
public class StockBkUtils {

    /**
     * 股票板块列表
     */
    private static final String BK_URL = "https://stockapi.com.cn/v1/base/bk";

    /**
     * 板块下的股票列表
     */
    private static final String BK_STOCK_URL = "https://stockapi.com.cn/v1/base/bkList?pageNo=1&pageSize=1000&bkCode=";

    public static void initBkList() {
        String body = HttpClientUtils.get(BK_URL);
        Result<JSONArray> result = JSON.parseObject(body, new TypeReference<Result<JSONArray>>() {});
        if (!result.getCode().equals("20000")) {
            log.error("BK_URL request error:" + body);
            return;
        }
        JSONArray jsonArray = result.getData();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            String code = object.getString("plateCode");
            String name = object.getString("name");
            System.out.println(code.toUpperCase() + "(\"" + code + "\",\"" + name + "\"),");
        }
    }

    /**
     * 获取板块下的股票代码
     *
     * @param bkName
     * @return
     */
    public static List<String> getStockListByBk(String bkName) {
        StockIndustryEnums stockBkEnums = StockIndustryEnums.getEnumByCodeOrName(bkName);
        ExceptionsEnhancer.notNull(stockBkEnums, "板块名称有误");
        String body = HttpClientUtils.get(BK_STOCK_URL + stockBkEnums.getCode());
        Result<JSONArray> result = JSON.parseObject(body, new TypeReference<Result<JSONArray>>() {});
        if (!result.getCode().equals("20000")) {
            log.error("BK_STOCK_URL request error:" + body);
            return null;
        }
        JSONArray jsonArray = result.getData();
        List<String> codes = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            String code = object.getString("f12");
            code = code.startsWith("60") ? "sh" + code : "sz" + code;
            codes.add(code);
        }
        return codes;
    }

    public static void main(String[] args) {
        //initBkList();
        List<String> codes = getStockListByBk("钢铁行业");
        System.out.println("'" + StringUtils.join(codes, "','") + "'");
    }
}
